using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using StudentManagement.Application.DTOs;
using StudentManagement.Application.Services;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace StudentManagement.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ClassController : ControllerBase
    {
        private readonly IClassService _classService;

        public ClassController(IClassService classService)
        {
            _classService = classService;
        }

        // GET: api/Class
        [HttpGet]
        [Authorize]
        public async Task<ActionResult<IEnumerable<ClassDTO>>> GetAllClasses()
        {
            var classes = await _classService.GetAllClassesAsync();
            return Ok(classes);
        }

        // GET: api/Class/{id}
        [HttpGet("{id}")]
        [Authorize]
        public async Task<ActionResult<ClassDTO>> GetClassById(int id)
        {
            var @class = await _classService.GetClassByIdAsync(id);
            if (@class == null)
            {
                return NotFound();
            }
            return Ok(@class);
        }

        // GET: api/Class/by-grade/{grade}
        [HttpGet("by-grade/{grade}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<ClassDTO>>> GetClassesByGrade(string grade)
        {
            var classes = await _classService.GetClassesByGradeAsync(grade);
            return Ok(classes);
        }

        // GET: api/Class/by-major/{major}
        [HttpGet("by-major/{major}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<ClassDTO>>> GetClassesByMajor(string major)
        {
            var classes = await _classService.GetClassesByMajorAsync(major);
            return Ok(classes);
        }

        // GET: api/Class/search/{keyword}
        [HttpGet("search/{keyword}")]
        [Authorize]
        public async Task<ActionResult<IEnumerable<ClassDTO>>> SearchClasses(string keyword)
        {
            var classes = await _classService.SearchClassesAsync(keyword);
            return Ok(classes);
        }

        // GET: api/Class/with-students/{id}
        [HttpGet("with-students/{id}")]
        [Authorize]
        public async Task<ActionResult<ClassDTO>> GetClassWithStudents(int id)
        {
            var @class = await _classService.GetClassWithStudentsAsync(id);
            if (@class == null)
            {
                return NotFound();
            }
            return Ok(@class);
        }

        // POST: api/Class
        [HttpPost]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<ClassDTO>> CreateClass([FromBody] ClassDTO classDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var createdClass = await _classService.CreateClassAsync(classDTO);
                return CreatedAtAction(nameof(GetClassById), new { id = createdClass.Id }, createdClass);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // PUT: api/Class/{id}
        [HttpPut("{id}")]
        [Authorize(Roles = "Admin,Teacher")]
        public async Task<ActionResult<ClassDTO>> UpdateClass(int id, [FromBody] ClassDTO classDTO)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            try
            {
                var updatedClass = await _classService.UpdateClassAsync(id, classDTO);
                if (updatedClass == null)
                {
                    return NotFound();
                }
                return Ok(updatedClass);
            }
            catch (System.Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // DELETE: api/Class/{id}
        [HttpDelete("{id}")]
        [Authorize(Roles = "Admin")]
        public async Task<IActionResult> DeleteClass(int id)
        {
            try
            {
                await _classService.DeleteClassAsync(id);
                return Ok(new { success = true });
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("班级不存在"))
                {
                    return NotFound();
                }
                return BadRequest(ex.Message);
            }
        }
    }
}